<template>
  <div>
    <!-- 面包屑导航栏 start -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item class="index" :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航栏 end -->

    <!-- 卡片主体区 start -->
    <el-card>
      <!-- 顶部搜索、重置、添加 start -->
      <el-row :gutter="20">
        <!-- 搜索 -->
        <el-col :span="6">
          <el-input placeholder="请输入用户名" v-model.trim="queryUserListObj.account" @change="keyDwon" clearable> </el-input>
        </el-col>
        <el-col :span="6">
          <el-input placeholder="请输入角色名" v-model.trim="queryUserListObj.role" @change="keyDwon" clearable> </el-input>
        </el-col>
        <!-- 重置 -->
        <el-col :span="2">
          <el-button class="btn-reset" @click="restInput($event)">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button class="btn-often" @click="getUserList($event)">搜索</el-button>
        </el-col>
        <!-- 添加 -->
        <el-col :span="2">
          <el-button class="btn-often" icon="el-icon-plus" @click="addUser($event)">添加</el-button>
        </el-col>
      </el-row>
      <!-- 顶部搜索、重置、添加 end -->

      <!-- 用户信息表格 start -->
      <el-table class="table-user" :data="userList" ref="tabListData" stripe style="width: 100%; min-height: 400px" max-height="420px" border>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="account" label="账号" width="80"> </el-table-column>
        <el-table-column prop="uname" label="真实姓名" width="80"> </el-table-column>
        <el-table-column prop="password" label="密码"> </el-table-column>
        <el-table-column prop="sex" label="性别" width="60"></el-table-column>
        <el-table-column prop="age" label="年龄" width="80" sortable></el-table-column>
        <el-table-column prop="phone" label="电话" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="role" label="角色" width="110"></el-table-column>
        <el-table-column prop="balance" label="余额(元)"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽:状态 -->
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.status === 1"></i>
            <i class="el-icon-error" v-else></i>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column prop="handle" label="操作" width="160px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="btn-text" @click="editUser($event, scope.row.id)" :disabled="scope.row.status !== 1">修改</el-button>
            <el-button type="text" class="btn-text" @click="deleteUser($event, scope.row.id)" :disabled="scope.row.status !== 1">删除</el-button>
            <el-tooltip effect="dark" content="可对用户修改角色" placement="top" :enterable="false">
              <el-button type="text" class="btn-text" @click="editUserRole($event, scope.row)" :disabled="scope.row.status !== 1">角色</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户信息表格 end -->

      <!-- 分页信息 start -->
      <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="queryUserListObj.pagenum" :page-sizes="[2, 5, 10, 20]" :page-size="queryUserListObj.pagesize" layout="sizes, prev, pager, next, jumper,total" :total="total"> </el-pagination>
      <!-- 分页信息 end -->
    </el-card>
    <!-- 卡片主体区 end -->

    <!-- 添加用户弹框 start -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="resetFormInput" :width="dialogWith">
      <!-- 添加用户表单 start -->
      <el-form ref="addFormRef" addFormRef class="add-form" label-width="80px" :model="addForm" :rules="addRules">
        <el-form-item label="账号" prop="account">
          <el-input v-model="addForm.account" placeholder="请输入账号" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="uname">
          <el-input v-model="addForm.uname" placeholder="请输入真实姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="openType==='add'">
          <el-input v-model="addForm.password" placeholder="请输入密码" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入电话" clearable></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age" placeholder="请输入年龄" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色" clearable filterable>
            <el-option v-for="(item, index) in allRoleList" :key="index" :label="item.rname" :value="item.rname"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="男">男</el-radio>ss
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 添加用户表单 end -->
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-reset" @click="cancel" size="small">取消</el-button>
        <el-button class="btn-often" @click="resetFormInput" size="small">重置</el-button>
        <el-button class="btn-often" type="primary" @click="saveAddUser" size="small">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加用户弹框 end -->

    <!-- 修改角色弹框 start -->
    <el-dialog title="修改角色" :visible.sync="rloeValue" @close="closeEdit()" width="25%">
      <div>
        <!-- 信息展示 start -->
        <p>当前用户账号：{{ roleInfo.account }}</p>
        <p>当前用户姓名：{{ roleInfo.uname }}</p>
        <p>当前角色：{{ roleInfo.role }}</p>
        <p>
          新的角色：
          <el-select v-model="roleInfo.role" placeholder="请选择角色" clearable filterable>
            <el-option v-for="(item, index) in allRoleList" :key="index" :label="item.rname" :value="item.rname"> </el-option>
          </el-select>
        </p>
        <!-- 信息展示 end -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn-reset" @click="cancelEdit($event)" size="small">取消</el-button>
        <el-button class="btn-often" type="primary" @click="saveRole($event)" size="small">确定</el-button>
      </div>
    </el-dialog>
    <!-- 修改角色弹框 end -->
  </div>
</template>

<script>
// 引入自定义js文件
import btn from '../utils/btn.js'
import _ from 'lodash'
export default {
  data() {
    // 校验真实姓名(中文或英文)
    const checkTrueName = (rule, val, callback) => {
      const reg = /^[\u4e00-\u9fa5a-zA-Z]+$/
      if (!val) {
        return callback(new Error('请输入真实姓名！'))
      } else if (!reg.test(val)) {
        return callback(new Error('只能输入中文或英文！'))
      } else {
        return callback()
      }
    }
    // 校验电话11位
    const checkPhone = (rule, val, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)([0-9]{9})$/
      if (!val) {
        return callback(new Error('请输入电话号码！'))
      } else if (!reg.test(val)) {
        return callback(new Error('电话号码不存在！'))
      } else {
        return callback()
      }
    }
    return {
      // 表单数据绑定
      addForm: {
        account: '',
        uname: '',
        password: '',
        phone: '',
        sex: '男',
        age: '',
        role: ''
      },
      // 表单验证规则绑定
      addRules: {
        // 账号不能为空
        account: [
          { required: true, message: '账号不能为空', triggger: 'blur' },
          { min: 2, max: 20, message: '账号在2~20个字符之间', triggger: 'blur' }
        ],
        // 密码不能为空
        password: [
          { required: true, message: '密码不能为空', triggger: 'blur' },
          { min: 5, max: 20, message: '密码在5~20个字符之间', triggger: 'blur' }
        ],
        // 真实姓名不能为空
        uname: [{ validator: checkTrueName, required: true, triggger: 'blur' }],
        // 电话不能为空
        phone: [{ validator: checkPhone, required: true, triggger: 'blur' }],
        // 性别不能为空
        sex: [{ required: true, message: '请选择性别', triggger: 'blur' }],
        // 年龄不能为空
        age: [{ required: true, message: '年龄不能为空', triggger: 'blur' }],
        role: [{ required: true, message: '角色不能为空', triggger: 'blur' }]
      },
      // 用户列表请求参数
      queryUserListObj: {
        account: '',
        role: '',
        pagesize: 5,
        pagenum: 1
      },
      //   列表信息
      userList: [],
      total: 0,
      //   勾选集合存储
      selectList: [],
      //   添加用户弹框的显示与否
      dialogFormVisible: false,
      //   添加用户列表
      addUserList: [],
      // 弹框宽度
      dialogWith: '50%',
      // 新增或修改的弹框的打开方式
      openType: '',
      // 弹框title
      dialogTitle: '',
      // 存储当前行id
      // 修改角色弹框表单
      rowId: '',
      // 修改角色弹框开关
      rloeValue: false,
      // 当前行角色信息
      roleInfo: {},
      // 角色信息下拉框值
      roleList: [],
      // 下拉框选中id
      // selectId: '',
      // 角色信息下拉框
      allRoleList: []
    }
  },
  created() {
    //   初始化查询用户列表
    this.getUserList()
    // 监听窗口大小改变
    this.changeDialogwith()
    // 获取角色信息下拉框
    this.getRoleList()
  },
  mounted() {
    // 监听窗口大小改变
    window.addEventListener('resize', () => {
      return () => {
        this.changeDialogwith()
      }
    })
  },
  methods: {
    // 重置清空
    resetFormInput() {
      this.$refs.addFormRef.resetFields()
    },
    //   获取用户列表
    async getUserList(e) {
      if (e) {
        //   取消焦点
        btn.preBtnFocus(e)
      }
      const res = await this.$http.post('getAllUser', {
        account: this.queryUserListObj.account,
        role: this.queryUserListObj.role,
        pageSize: this.queryUserListObj.pagesize,
        pageNum: this.queryUserListObj.pagenum
      })
      if (!res.data) {
        this.$message.error('获取用户列表失败，请重新操作！')
      } else {
        //   数据赋值
        this.userList = res.data
        this.userList.forEach((item) => {
          item.balance = item.balance.toFixed(2)
        })
        this.pagenum = res.data.pageNum
        const list = await this.$http.post('selectAllUser', {})
        this.total = list.data.length
      }
    },
    // 重置
    restInput(e) {
      this.queryUserListObj.account = ''
      this.queryUserListObj.role = ''
      // 刷新表格数据
      this.getUserList()
      //   取消焦点
      btn.preBtnFocus(e)
    },
    // 状态开关值改变
    async statusChange(row) {
      // console.log('row', row)
      //   修改用户状态
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      //   console.log('res', res)
      if (res.meta.status !== 200) {
        //   重置状态
        row.mg_state = !row.mg_state
        return this.$message.error('操作失败，请重新操作！')
      } else {
        if (row.mg_state) {
          return this.$message.success('操作成功！账号成功解冻！')
        } else {
          return this.$message.success('操作成功！账号成功冻结！')
        }
      }
    },
    // 行点击事件勾选  暂时不需要
    // rowClick(row, column, event) {
    //   this.$refs.tabListData.toggleRowSelection(row)
    // },
    // 输入框回车事件
    keyDwon() {
      this.getUserList()
    },
    addUser(e) {
      btn.preBtnFocus(e)
      // 存储打开方式
      this.openType = 'add'
      // 修改弹框title
      this.dialogTitle = '添加用户'
      this.dialogFormVisible = true
    },
    // 添加用户
    saveAddUser() {
      // 新增
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const data = { ...this.addForm }
          data.age = Number(data.age)
          if (this.openType === 'add') {
            const res = await this.$http.post('register', data)
            if (res.data === '添加成功!') {
              this.$message.success('添加成功！')
              this.dialogFormVisible = false
              this.getUserList()
            } else if (res.data === '账号名已存在!') {
              this.$message.warning('账号名已存在！请修改账号名！')
            } else {
              this.$message.warning('用户已存在！请勿反复添加！')
            }
          } else if (this.openType === 'edit') {
            // 编辑
            // console.log('编辑')
            const data = _.cloneDeep(this.addForm)
            data.age = Number(data.age)
            const res = await this.$http.post('updateUser', data)
            // console.log(res)
            if (res.data === '修改信息成功！') {
              this.$message.success('修改成功！')
              this.dialogFormVisible = false
              this.getUserList()
            } else {
              this.$message.error('修改失败,请重新操作！')
            }
          }
        }
      })
    },
    // 操作列
    async editUser(e, id) {
      btn.preBtnFocus(e)
      // 存储打开方式
      this.openType = 'edit'
      this.rowId = id
      // 修改弹框title
      this.dialogTitle = '修改用户信息'
      this.dialogFormVisible = true
      // 获取详情
      const res = await this.$http.get('getUserDetail', {
        params: {
          id: id
        }
      })
      // console.log('获取详情结果', res)
      if (res.data) {
        this.addForm = res.data
        this.addForm.age = String(res.data.age)
      } else {
        this.$message.error('获取信息失败，请重新操作!')
      }
    },
    // 删除用户
    async deleteUser(e, id) {
      btn.preBtnFocus(e)
      const result = await this.$confirm('你确定要删除该用户吗？删除后无法恢复！', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((error) => error)
      // console.log('结果', result)
      if (result !== 'confirm') {
        this.$message.info('已取消删除操作！')
      } else {
        // 删除
        const res = await this.$http.get('deleteUser', {
          params: {
            id: id
          }
        })
        // console.log(res)
        if (res.data === '删除成功！') {
          this.getUserList()
          this.$message.success('删除成功！')
        } else {
          this.$message.error('删除失败，请重新操作！')
        }
      }
    },
    // 修改用户
    async editUserRole(e, row) {
      btn.preBtnFocus(e)
      // 保存行数据
      this.roleInfo = _.cloneDeep(row)
      // 打开弹窗
      this.rloeValue = true
    },
    // 监听pagesize改变事件
    pageSizeChange(pageSize) {
      this.queryUserListObj.pagesize = pageSize
      // 重新分页查询
      this.getUserList()
    },
    // 监听当前页改变事件
    pageCurrentChange(pageNum) {
      console.log('pageNum', pageNum)
      this.queryUserListObj.pagenum = pageNum
      // 重新分页查询
      this.getUserList()
    },
    cancel() {
      this.dialogFormVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 改变弹窗大小
    changeDialogwith() {
      // 获取当前窗口大小
      const val = document.body.clientWidth
      console.log('val', val)
      if (val <= 1000) {
        this.dialogWith = '500px'
        console.log('with', this.dialogWith)
      }
    },
    // 取消
    cancelEdit(e) {
      btn.preBtnFocus(e)
      this.rloeValue = false
      // this.selectId = ''
    },
    closeEdit() {
      // this.selectId = ''
      this.roleInfo = {}
    },
    // 保存修改角色
    async saveRole(e) {
      btn.preBtnFocus(e)
      const data = _.cloneDeep(this.roleInfo)
      data.rname = _.cloneDeep(this.roleInfo.role)
      const res = await this.$http.post('updateUser', data)
      if (res.data === '修改信息成功！') {
        this.$message.success('修改角色成功！')
        this.rloeValue = false
        this.getUserList()
      } else {
        this.$message.error('修改角色失败,请重新操作！')
      }
    },
    async getRoleList() {
      //   获取角色信息
      const res = await this.$http.post('getAllRole')
      if (res.data) {
        this.allRoleList = res.data
      } else {
        this.$message.error('获取角色信息失败！')
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 按钮
.btn-fault {
  margin-left: 561px;
}
// 添加用户表单
.add-form {
  box-sizing: border-box;
  width: 100%;
  padding: 0px 40px 0px 10px;
}
// 表单样式
.el-form {
  display: flex;
  flex-wrap: wrap;
}
.el-form-item {
  width: 50%;
}

// 图标
.el-icon-success {
  color: #9acc99;
}
.el-icon-error {
  color: red;
}
</style>
